package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.ChengXinCollectionTagEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.ClOrderInputVo;
import com.jy.admin.services.cashPocket.vo.ClOrderReceiveRequest;
import com.jy.admin.services.cashPocket.vo.ClRepaymentRequest;
import com.jy.admin.services.cashPocket.vo.ClUserInfoInputVo;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.*;


/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class ChenXingNewService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChenXingNewService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private CeRepaymentLinkDao repaymentLinkDao;

    private String captchakey = "";

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("chenxingnew", this);
    }

    public String getCaptchakeyBase() {
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode("chenxingnew");
        String url = ceMerchantEntity.getApiDomain() + "/login/captcha/info";
        Map<String, String> headers = Maps.newHashMap();
        JSONObject params = new JSONObject();
        String result = HttpUtil.postPageBody(url, headers, params.toString());
        if (JsonIterator.deserialize(result).get("code").toInt() == 1) {
            Any cont = JsonIterator.deserialize(result).get("response").get("cont");
            captchakey = cont.get("captchakey").toString();
            String captchacont = "data:image/png;base64," + cont.get("captchacont").toString();
            return captchacont;

        }
        return JsonIterator.deserialize(result).get("msg").toString();
    }

    public String login(CeAgentAccountEntity agentAccount, String code) {
        if (StringUtils.isEmpty(code)) {
            return "请输入验证码";
        }
        if (!captchakey.equals("")) {
            CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String url = ceMerchantEntity.getApiDomain() + "/login/doLogin?userName=" + agentAccount.getAccount() + "&password=" + agentAccount.getPassword() +
                    "&captchakey=" + captchakey + "&captcha=" + code + "&step=1";
            Map<String, String> headers = getHeaders(agentAccount);
            headers.remove("token");
            JSONObject params = new JSONObject();
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            LOGGER.info("== ChenXing登录==,res:{}", result);
            if (JsonIterator.deserialize(result).get("code").toInt() == 1) {
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("token", JsonIterator.deserialize(result).get("response").get("cont").get("token").toString());
                requestHeader.put("Content-Type", "application/json");
                requestHeader.put("lang", "en");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return "登录成功";
            }
        }
        LOGGER.info("== ChenXing登录 验证码获取失败==");

        return "登录失败";
    }


    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/dh/order/dhUserData";
        LOGGER.info("== 开始检测Token是否有效 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.postPageBody(url, headers, params.toString());
        LOGGER.info("== 结束检测Token是否有效 ==,result:{}", result);

        if (JsonIterator.deserialize(result).get("response").size() == 0) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.user_info.getType());
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return false;
        }
        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== InfinityCashService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }

    public static void main(String[] args) {

        String str = "Udai";
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (String.valueOf(str.charAt(i)).equals(" ")) {
                stringBuffer.append("%20");
            } else {
                stringBuffer.append(str.charAt(i));
            }

        }
        LOGGER.info("== 姓名拼接的结果 ==,str:{}", stringBuffer);
//        {"token":"f1399ded-0677-4099-9e0f-649d008ff525","space":"rupeestar","Content-Type":"application/json"}
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/dh/order/list?pageSize=200&pageNumber=1";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
        Map<String, String> headers = getHeaders(agentAccount);
        JSONObject params = new JSONObject();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        String result = HttpUtil.postPageBody(url, headers, params.toString());
        Any resultJson = JsonIterator.deserialize(result).get("response");
        if (resultJson == null) {
            LOGGER.error("== 订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        List<Any> resultsList = resultJson.get("list").asList();
        LOGGER.info("== 未还款订单列表 ==,screeningList:{}", JsonStream.serialize(resultsList));
        LOGGER.info("== 未还款订单列表数量 ==,size:{}", resultsList.size());


//        String historyUrl = merchant.getApiDomain() + "/cms/preCollection/tasks/history?pageIndex=1&pageSize=200";
//        String historyResult = HttpUtil.getPage(historyUrl,params, headers);
//        Any historyResultJson = JsonIterator.deserialize(historyResult).get("data");
//        if (historyResultJson == null) {
//            LOGGER.error("== 已还款订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
//            return;
//        }
//        List<Any> historyResultsList = historyResultJson.get("list").asList();
//        LOGGER.info("== 已还款订单列表数量 ==,historyResultsList:{}", JsonStream.serialize(historyResultsList));
//        LOGGER.info("== 已还款订单列表数量 ==,size:{}", historyResultsList.size());
//        historyResultsList.forEach(item -> {
//            if (DateUtil.getDate(new Date(item.get("outTime").toLong() * 1000), "yyyy-MM-dd").equals(DateUtil.getDate("yyyy-MM-dd"))) {
//                LOGGER.info("== 获取当天已还款订单列表 ==,historyResultsList:{}", item.toString());
//                resultsList.add(item);
//            }
//        });


        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //更新数据
        LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());

        //对比订单数据
        if (resultsList.size() >= activeOrders.size()) {
            LOGGER.info("== 存在未拉取订单 ==，size:{}", resultsList.size());
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("loanOrderNo").toString();
                    CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (todayOneByOrderNo == null) {
                        LOGGER.info("==更新的时候发现有新的订单==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    } else {
                        LOGGER.info("==更新的时候订单的已存在==,agentCode:{},orderNo:{}", todayOneByOrderNo.getAgentCode(), orderNo);
                        if (item.get("isRepay").toInt() == 1) {
                            LOGGER.info("==更新的时候订单的已存在，状态为已还款==,account:{},orderNo:{},status:{}", todayOneByOrderNo.getAgentCode(), orderNo, item.get("isRepay").toString());
                            todayOneByOrderNo.setOrderInfo(item.toString())
                                    .setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(todayOneByOrderNo);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });
        } else {
            LOGGER.info("== 订单减少 ==，size:{}", resultsList.size());
            activeOrders.forEach(item -> {
                try {
                    String id = JsonIterator.deserialize(item.getOrderInfo()).get("loanOrderNo").toString();
                    boolean hasOrder = false;
                    Any currentOrder = null;
                    for (int i = 0; i < resultsList.size(); i++) {
                        Any child = resultsList.get(i);
                        String orderNo = child.get("loanOrderNo").toString();
                        if (id.equals(orderNo)) {
                            LOGGER.info("== 当前订单存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                            hasOrder = true;
                            currentOrder = child;
                            break;
                        }

                    }
                    if (!hasOrder) {
                        LOGGER.info("== 当前订单不存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), id);
                        if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            item.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    } else {
                        LOGGER.info("==更新的时候订单的已存在==,agentCode:{},orderNo:{}", item.getAgentCode(), id);
                        if (currentOrder.get("isRepay").toInt() == 1) {
                            LOGGER.info("==更新的时候订单的已存在，状态为已还款==,account:{},orderNo:{},status:{}", agentAccount.getAccount(), id, currentOrder.get("repayState").toString());
                            item.setOrderInfo(currentOrder.toString())
                                    .setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
                }
            });

        }
        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));


        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();


                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                String loanOrderNo = orderInfo.get("loanOrderNo").toString();
                JSONObject param = new JSONObject();
                String repaymentInfoUrl = merchant.getApiDomain() + "/share/order/info?loanOrderNo=" + loanOrderNo + "&infoType=dh";
                String repaymentInfoResult = HttpUtil.postPageBody(repaymentInfoUrl, headers, param.toString());
                LOGGER.info("== 获取成功 repaymentInfo==");
                if (JsonIterator.deserialize(repaymentInfoResult).get("code").toInt() != 1) {
                    return;
                }
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoResult).get("response").get("cont");
                if (repaymentInfo.toString().equals("null")) {
                    return;
                }
                String remainMoney = repaymentInfo.get("cont").get("repayAmount").toString();
                updateRemainMoney(order.getCollectionNo(), remainMoney);

                if (!hasDetailData) {
                    CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                    if (baseInfoDetail == null) {
                        infoMap.put("baseInfo", repaymentInfo.toString());
                        LOGGER.info("== 获取成功 baseInfo==");

                        List<String> images = Lists.newArrayList();
                        if (!repaymentInfo.get("frontImg").toString().equals("")) {
                            images.add(repaymentInfo.get("frontImg").toString());
                        }
                        if (!repaymentInfo.get("backImg").toString().equals("")) {
                            images.add(repaymentInfo.get("backImg").toString());
                        }
                        if (!repaymentInfo.get("livenessImg").toString().equals("")) {
                            images.add(repaymentInfo.get("livenessImg").toString());
                        }
                        if (!repaymentInfo.get("panCardImg").toString().equals("")) {
                            images.add(repaymentInfo.get("panCardImg").toString());
                        }
                        infoMap.put("images", JsonStream.serialize(images));
                        LOGGER.info("== 获取成功 images==");
                    } else {
                        baseInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(baseInfoDetail);
                    }

                    CeOrdersDetailEntity contactInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                    if (contactInfoDetail == null) {
                        LOGGER.info("== 获取成功 emergencyInfo==");
                        infoMap.put("contactInfo", repaymentInfo.get("contactJson").toString());
                    } else {
                        contactInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactInfoDetail);
                    }

                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        String contactInfoUrl = merchant.getApiDomain() + "/share/order/deviceInfo?loanOrderNo=" + loanOrderNo;
                        JSONObject contactParams = new JSONObject();
                        String contactInfo = HttpUtil.postPageBody(contactInfoUrl, headers, contactParams.toString());

                        LOGGER.info("== 获取成功 chenxingnew contactInfo==,contactInfo:{}",contactInfo);

                        try {
                            String phoneListPath = JsonIterator.deserialize(contactInfo).get("response").get("cont").get("phoneListPath").toString();
                            if (phoneListPath.equals("null")) {
                                List<Any> callLog = repaymentInfo.get("contactJson").asList();
                                JSONArray callLogs = new JSONArray();
                                for (Any vo : callLog) {
                                    JSONObject j1 = new JSONObject();
                                    if (!vo.get("contactName").toString().equals("") && !vo.get("contactPhone").toString().equals("")) {
                                        j1.put("name", vo.get("contactName").toString());
                                        j1.put("phone", vo.get("contactPhone").toString());
                                        callLogs.add(j1);
                                    }
                                }
                                LOGGER.info("== Chenxing 获取通话记录 ==,url:{}", callLogs);
                                JSONObject jsonData = new JSONObject();
                                jsonData.put("contacts", callLogs);

                                String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                infoMap.put("contactUrl", contactUrl);

                            } else {
                                String page = HttpUtil.getTxt(phoneListPath);
                                LOGGER.info("== 获取通讯录列表 ==,url:{},list:{}",phoneListPath, page);

                                List<Any> list = JsonIterator.deserialize(page).asList();
                                if (CollectionUtils.isNotEmpty(list)) {
                                    JSONArray contacts = new JSONArray();
                                    for (Any vo : list) {
                                        JSONObject j1 = new JSONObject();
                                        j1.put("name", vo.get("name").toString());
                                        if (!vo.get("number").toString().equals("")) {
                                            j1.put("phone", vo.get("number").toString());
                                            contacts.add(j1);
                                        }
                                    }
                                    JSONObject jsonData = new JSONObject();
                                    jsonData.put("contacts", contacts);

                                    String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                    LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                    infoMap.put("contactUrl", contactUrl);
                                } else {
                                    String callLogUrl = merchant.getApiDomain() + "/share/order/dhContactRecord?loanOrderNo=" + loanOrderNo + "&pageSize=200&pageNumber=1";
                                    JSONObject callLogParams = new JSONObject();
                                    String callLogInfo = HttpUtil.postPageBody(callLogUrl, headers, callLogParams.toString());
                                    List<Any> callLog = JsonIterator.deserialize(callLogInfo).get("response").get("list").asList();
                                    if (CollectionUtils.isNotEmpty(callLog)) {
                                        JSONArray callLogs = new JSONArray();
                                        for (Any vo : callLog) {
                                            JSONObject j1 = new JSONObject();
                                            if (!vo.get("phone").toString().equals("") && !vo.get("name").toString().equals("")) {
                                                j1.put("name", vo.get("name").toString());
                                                if (vo.get("callDuration").toInt() > 0 && vo.get("callType").toInt() != 2) {
                                                    j1.put("phone", vo.get("phone").toString());
                                                    callLogs.add(j1);
                                                }

                                            }
                                        }
                                        LOGGER.info("== Chenxing 获取通话记录 ==,url:{}", callLogs);
                                        JSONObject jsonData = new JSONObject();
                                        jsonData.put("contacts", callLogs);

                                        String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                        LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                        infoMap.put("contactUrl", contactUrl);
                                    } else {
                                        String contacts;
                                        if (contactInfoDetail != null) {
                                            contacts = contactInfoDetail.getDetailInfo();
                                        } else {
                                            contacts = infoMap.get("contactInfo");

                                        }
                                        JSONObject jsonData = new JSONObject();
                                        jsonData.put("contacts", contacts);

                                        String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                                        LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                        infoMap.put("contactUrl", contactUrl);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("appName").toString() + "[" + orderDetail.get("productName").toString() + "]";
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");


                CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any baseInfo = JsonIterator.deserialize(baseInfoDetail.getDetailInfo());
                String borrowCapital = baseInfo.get("loanAmount").toString();
                String actualAmount = baseInfo.get("actualAmount").toString();
                String paidAmount = new BigDecimal(baseInfo.get("loanAmount").toString()).add(new BigDecimal(baseInfo.get("overdueAmount").toString())).subtract(new BigDecimal(baseInfo.get("repayAmount").toString())).toString();
                String repaymentAmount = new BigDecimal(baseInfo.get("loanAmount").toString()).add(new BigDecimal(baseInfo.get("overdueAmount").toString())).toString();
                String balanceAmount = baseInfo.get("repayAmount").toString();
                String overdueDays = orderDetail.get("dhDays").toString();
                String loanInterest = "0";
                String overdueAmount = orderDetail.get("overdueAmount").toString();
                String userType = orderDetail.get("userType").toString();
                String bagLink = orderDetail.get("bagLink").toString();
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, overdueAmount);
                String overdueRatio = "0";
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(overdueAmount).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }
                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(userType.equals("new") ? 1 : 2)
                        .setBorrowCapital(borrowCapital)
                        .setAppLink(bagLink)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest(loanInterest)
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee("0")
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(baseInfo.get("createTime").toString())
                        .setRepaymentDate(baseInfo.get("repayTime").toString())
                        .setRemainMoney(balanceAmount)
                        .setTotalMoney(repaymentAmount);

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());

                String aadhaarNo = baseInfo.get("idNumber").toString();
                String pancardNo = baseInfo.get("panNumber").toString();
                String email = baseInfo.get("email").toString();
                String mobile = baseInfo.get("phone").toString();
                String name = baseInfo.get("name").toString();
                String state = "no";
                String gender = baseInfo.get("gender").toString();
                int maritalStatus = 0;
                int education = 0;
                String address = baseInfo.get("addressDetail").toString();
                String pinCode = "no";
                String city = "no";
                String dateOfBirth = baseInfo.get("dateOfBirth").toString();

                Date birthDate = DateUtil.getDate(dateOfBirth, "dd-MM-yyyy");
                String birthDay = DateUtil.getDate(birthDate, "yyyy-MM-dd");

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("contactName").toString();
                    parentPhone = contactInfoJson.get(0).get("contactPhone").toString();
                    friendName = contactInfoJson.get(1).get("contactName").toString();
                    friendMobile = StringUtils.isEmpty(contactInfoJson.get(1).get("contactPhone").toString().trim()) ? "no" : contactInfoJson.get(1).get("contactPhone").toString();
                }


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(education)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(maritalStatus)
                        .setMarriedStatus(maritalStatus)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex("female".equals(gender) ? 0 : 1)
                        .setContactUrl(contactUrlEntity.getDetailInfo())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        waitingPaidCheckOrders.forEach(order -> {
            Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
            String url = merchant.getApiDomain() + "/share/order/loanRecord?loanOrderNo=" + orderInfo.get("loanOrderNo").toString();
            JSONObject params = new JSONObject();
            LOGGER.info("== 开始请求订单详情 ==,url:{}", url);
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            Any resultJson = JsonIterator.deserialize(result);
            if (resultJson.get("code").toInt() != 1) {
                LOGGER.info("== 订单详情异常 ==");
                return;
            }
            List<Any> cont = resultJson.get("response").get("list").asList();
            Any currentOrder=null;
            for (int i = 0; i < cont.size(); i++) {
                if (cont.get(i).get("loanOrderNo").toString().equals(order.getOrderNo())){
                    currentOrder = cont.get(i);
                }
            }
            if (currentOrder!= null) {
                if (currentOrder.get("isRepay").toInt() == 1) {
                    order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                    order.setStatus(OrderStatusEnum.paid_update.getStatus());
                    ordersDao.updateByPrimaryKey(order);
                    return;
                } else {
                    if (currentOrder.get("status").toString().equals("4")) {
                        order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                        order.setStatus(OrderStatusEnum.paid_update.getStatus());
                        ordersDao.updateByPrimaryKey(order);
                        return;
                    }
                }
            }

            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String paidAmount = new BigDecimal(repaymentInfo.get("loanAmount").toString()).add(new BigDecimal(repaymentInfo.get("overdueAmount").toString())).subtract(new BigDecimal(repaymentInfo.get("repayAmount").toString())).toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
//                String paidAmount = repaymentInfo.get("paidAmount").toString().equals("") ? "0" : repaymentInfo.get("paidAmount").toString());
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        ChengXinCollectionTagEnum currentTag = ChengXinCollectionTagEnum.RNR_V2;

        for (ChengXinCollectionTagEnum e : ChengXinCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNoAndAgentCode(ceCommentPushLogEntity.getOriginNo(), account.getAgentCode());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        try {
            Map<String, String> headers = getHeaders(account);
            JSONObject params = new JSONObject();
            LOGGER.info("== ChenXing 开始同步催记到甲方D ==,params:{}", JsonStream.serialize(params));
            String name = orderInfo.get("name").toString();
            StringBuffer exName = new StringBuffer();
            for (int i = 0; i < name.length(); i++) {
                if (String.valueOf(name.charAt(i)).equals(" ")) {
                    exName.append("%20");
                } else {
                    exName.append(name.charAt(i));
                }

            }
            String noteUrl = ceMerchantEntity.getApiDomain() + "/dh/order/contactRecord/save?dhOrderNo=" + orderInfo.get("dhOrderNo").toString() +
                    "&contactTarget=IAM&contactType=1&remark=" + currentTag.getShortDesc() + "&contactResult=" + currentTag.getDesc() + "&contactPhone=" + orderInfo.get("phone").toString()
                    + "&contactName=" + exName;
            String result = HttpUtil.postPageBody(noteUrl, headers, params.toString());
            LOGGER.info("== ChenXing 开始同步催记到甲方 ==,res:{}", result);

            if ("1".equals(JsonIterator.deserialize(result).get("code").toString())) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==,msg:{}", JsonIterator.deserialize(result).get("msg").toString());
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());

        Map<String, String> headers = getHeaders(accountEntity);

        String channelUrl = ceMerchantEntity.getApiDomain() + "/dh/order/list/conditions";
        LOGGER.info("== 获取ChenXing还款渠道列表 ==,url:{}", channelUrl);
        String channelResult = HttpUtil.postPageBody(channelUrl, headers, "");
        LOGGER.info("== 获取ChenXing还款渠道列表 ==,url:{},res:{}", channelUrl, channelResult);
        Any channelResultJson = JsonIterator.deserialize(channelResult);
        List<Any> channelList = null;
        if (channelResultJson.get("code").toInt() == 1) {
            channelList = channelResultJson.get("response").get("list").asList();
            LOGGER.info("== 获取ChenXing还款渠道列表 ==,list:{}", channelList);
        }

        if (channelList == null) {
            LOGGER.info("== 获取ChenXing还款渠道列表出错 ==,list:{}", channelList);
            return "";
        }


        String link = "";

        if (apolloConfigUtil.isSingleRepayLink()) {
            JSONObject params = new JSONObject();
            String url = ceMerchantEntity.getApiDomain() + "/share/postLoan/generate/repayLink?repayType=0&loanOrderNo=" + orderInfoJson.get("loanOrderNo").toString() + "&channels=" + channelList.get(0).get("channel");
            LOGGER.info("== 获取ChenXing还款链接 ==,url:{}", url);
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            LOGGER.info("== 获取ChenXing还款链接 ==,url:{},res:{}", url, result);
            Any resultJson = JsonIterator.deserialize(result);
            if (!"".equals(resultJson.get("response").toString())) {
                link = resultJson.get("response").get("cont").toString();
                LOGGER.info("== 获取还款链接 ==,link:{}", link);
            }
            return link;
        }
        for (int i = 0; i < channelList.size(); i++) {
            JSONObject params = new JSONObject();
            String url = ceMerchantEntity.getApiDomain() + "/share/postLoan/generate/repayLink?repayType=0&loanOrderNo=" + orderInfoJson.get("loanOrderNo").toString() + "&channels=" + channelList.get(i).get("channel");
            LOGGER.info("== 获取ChenXing还款链接 ==,url:{}", url);
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            LOGGER.info("== 获取ChenXing还款链接 ==,url:{},res:{}", url, result);
            Any resultJson = JsonIterator.deserialize(result);
            if (resultJson.get("code").toInt() == 1) {
                link += channelList.get(i).get("channel").toString() + ":" + resultJson.get("response").get("list").asList().get(0).get("path").toString() + ", \n";
                LOGGER.info("== 获取还款链接 ==,link:{}", link);
            }
        }
        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo, boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());

        Map<String, String> headers = getHeaders(accountEntity);

        String channelUrl = ceMerchantEntity.getApiDomain() + "/dh/order/list/conditions";
        LOGGER.info("== 获取ChenXing还款渠道列表 ==,url:{}", channelUrl);
        String channelResult = HttpUtil.postPageBody(channelUrl, headers, "");
        LOGGER.info("== 获取ChenXing还款渠道列表 ==,url:{},res:{}", channelUrl, channelResult);
        Any channelResultJson = JsonIterator.deserialize(channelResult);
        List<Any> channelList = null;
        if (channelResultJson.get("code").toInt() == 1) {
            channelList = channelResultJson.get("response").get("list").asList();
            LOGGER.info("== 获取ChenXing还款渠道列表 ==,list:{}", channelList);
        }

        if (channelList == null) {
            LOGGER.info("== 获取ChenXing还款渠道列表出错 ==,list:{}", channelList);
            return "";
        }

        String link = "";
        for (int i = 0; i < channelList.size(); i++) {
            JSONObject params = new JSONObject();
            String url = ceMerchantEntity.getApiDomain() + "/share/postLoan/generate/repayLink?repayType=2&loanOrderNo=" + orderInfoJson.get("loanOrderNo").toString() + "&channels=" + channelList.get(i).get("channel");
            LOGGER.info("== 获取ChenXing展期链接 ==,url:{}", url);
            String result = HttpUtil.postPageBody(url, headers, params.toString());
            LOGGER.info("== 获取ChenXing展期链接 ==,url:{},res:{}", url, result);
            Any resultJson = JsonIterator.deserialize(result);
            if (resultJson.get("code").toInt() == 1) {
                link += channelList.get(i).get("channel").toString() + ":" + resultJson.get("response").get("list").asList().get(0).get("path").toString() + ", \n";
                LOGGER.info("== 获取ChenXing展期链接 ==,link:{}", link);
            }

        }
        return link;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }

    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }
//    public static void main(String[] args) {
//        String dateOfBirth = "24-06-1988";
//
//        Date birthDate = DateUtil.getDate(dateOfBirth, "dd-MM-yyyy");
//        String birthDay = DateUtil.getDate(birthDate, "yyyy-MM-dd");
//        LOGGER.info("== ==,BIR:{}", birthDay);
//    }
}
